package com.cupk.services;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class EmailService {

    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    public void sendVerificationCode(String to, String code) {
        // 在开发环境中，总是记录验证码以便测试
        log.info("=== 开发环境验证码 ===");
        log.info("邮箱: {}", to);
        log.info("验证码: {}", code);
        log.info("===================");

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject("您的验证码 - 学术科研管理系统");
            message.setText("您正在进行操作，验证码是：" + code + "，该验证码将在5分钟内失效。");
            mailSender.send(message);
            log.info("验证码邮件已发送到: {}", to);
        } catch (Exception e) {
            log.warn("邮件发送失败，但在开发环境中继续执行。验证码: {} 发送到: {}", code, to);
            log.warn("邮件发送错误详情: {}", e.getMessage());
            // 在开发环境中不抛出异常，允许继续执行
        }
    }
}